package com.example.gateway.filter;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.nacos.shaded.com.google.common.collect.Lists;
import com.example.gateway.service.ValidateCodeService;
import lombok.Data;
import lombok.extern.log4j.Log4j2;
import org.apache.dubbo.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Flux;

import java.nio.CharBuffer;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;

/**
 * 验证码验证拦截器
 */
@Component
@Log4j2
public class CodeVerificationGatewayFilterFactory extends AbstractGatewayFilterFactory<CodeVerificationGatewayFilterFactory.Config> {
    public CodeVerificationGatewayFilterFactory() {
        super(Config.class);
    }

    @Autowired
    private ValidateCodeService validateCodeService;
    @Override
    public List<String> shortcutFieldOrder() {
        return Lists.newArrayList("enabled");
    }

    private final static String[] VALIDATE_URL = new String[] { "/login" };
    private final static String CODE = "code";
    private final static String UUID = "uuid";
    @Override
    public GatewayFilter apply(Config config) {
        return (exchange, chain) -> {
            ServerHttpRequest request = exchange.getRequest();
            if(StringUtils.isContains(VALIDATE_URL,request.getURI().getPath())){
                String rspStr = resolveBodyFromRequest(request);
                JSONObject jsonObject = JSON.parseObject(rspStr);
                validateCodeService.checkCaptcha(jsonObject.getString(CODE),jsonObject.getString(UUID));
            }
            log.info("每次路由匹配到会执行");
            Boolean enabled = config.getEnabled();
            log.info("从配置文件中获取到的 enabled 的值=[{}].", enabled);
            return chain.filter(exchange);
        };
    }
    @Data
    public static class Config {
        private Boolean enabled;
    }

    private String resolveBodyFromRequest(ServerHttpRequest serverHttpRequest)
    {
        // 获取请求体
        Flux<DataBuffer> body = serverHttpRequest.getBody();
        AtomicReference<String> bodyRef = new AtomicReference<>();
        body.subscribe(buffer -> {
            CharBuffer charBuffer = StandardCharsets.UTF_8.decode(buffer.readableByteBuffers().next());
            DataBufferUtils.release(buffer);
            bodyRef.set(charBuffer.toString());
        });
        return bodyRef.get();
    }

}
